package org.nowcoder.leetcode.BTree;

import java.util.ArrayDeque;
import java.util.Map;

/**
 * Title  : 104. Maximum Depth of Binary Tree
 * Source : https://leetcode.cn/problems/maximum-depth-of-binary-tree/?envType=study-plan-v2&envId=top-interview-150
 * Author : XrazYang
 * Date   : 2023-08-29
 */
public class LeetCode_104 {
    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public int maxDepth(TreeNode root) {
        //深度优先：递归实现
        // if (root == null) {
        //     return 0;
        // }
        // return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;

        //深度优先: 非递归实现
        if (root == null) {
            return 0;
        }
        int max = 0;
        ArrayDeque<Map.Entry<TreeNode, Integer>> sta = new ArrayDeque<>();
        sta.push(Map.entry(root, 1));
        while (!sta.isEmpty()) {
            Map.Entry<TreeNode, Integer> entry = sta.pop();
            TreeNode node = entry.getKey();
            Integer depth = entry.getValue();
            max = Math.max(max, depth);
            if (node.left != null) {
                sta.push(Map.entry(node.left, depth + 1));
            }
            if (node.right != null) {
                sta.push(Map.entry(node.right, depth + 1));
            }
        }
        return max;
    }
}
